import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/match/detail/lq_detail_head_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/match/detail/lq_match_detail_logic.dart';
import 'package:ball_lion/module/match_detail/live/animate_live_view.dart';
import 'package:ball_lion/module/match_detail/live/match_live_view.dart';
import 'package:ball_lion/module/live/items/gift_effect_view.dart';
import 'package:ball_lion/module/match_detail/basketball/lq_detail_head_widget.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/share/share_button.dart';

class LqDetailPage extends StatefulWidget {
  const LqDetailPage({super.key});

  @override
  State<LqDetailPage> createState() => _LqDetailPageState();
}

class _LqDetailPageState extends State<LqDetailPage>
    with TickerProviderStateMixin {
  late LqMatchDetailLogic logic;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqMatchDetailLogic>(
        tag: Get.arguments.toString(),
        initState: (state) {
          logic = Get.put(LqMatchDetailLogic(), tag: Get.arguments.toString());
        },
        builder: (logic) {
          return PrimaryScrollController(
              controller: logic.scrollC,
              child: Scaffold(
                  backgroundColor: logic.isPlayVideo
                      ? Colours.white
                      : Colours.main, //防止中间有一条缝
                  body: ExtendedNestedScrollView(
                    pinnedHeaderSliverHeightBuilder: () =>
                        MediaQuery.of(context).padding.top +
                        kToolbarHeight +
                        (logic.isPlayVideo ? 199 : 0),
                    controller: logic.scrollC,
                    physics: const NeverScrollableScrollPhysics(),
                    headerSliverBuilder: (context, innerBoxIsScrolled) {
                      return [
                        logic.isPlayVideo ? liveStreamHeader() : matchHeader()
                      ];
                    },
                    body: Stack(
                      children: [
                        MediaQuery.removePadding(
                          removeTop: true,
                          context: context,
                          child: Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                            ),
                            child: LoadingWidget<bool>(
                              isLoading: logic.isLoading,
                              data: false,
                              child: () => Column(
                                children: [
                                  SizedBox(
                                    height: 40,
                                    width: double.infinity,
                                    child: Styles.tabbar(
                                      controller: logic.tabController,
                                      labelPadding: EdgeInsets.zero,
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceAround,
                                      tabs: List.generate(
                                          logic.tabs.length,
                                          (index) => Stack(
                                                alignment:
                                                    AlignmentDirectional.center,
                                                children: [
                                                  QsText(
                                                    logic.tabs[index],
                                                    needCenter: true,
                                                  ),
                                                  if (logic.tabsClick.contains(
                                                          logic.tabs[index]) &&
                                                      SpUtils.getMatchClick(
                                                                  logic.tabs[
                                                                      index])
                                                              ?.contains(
                                                                  "${logic.matchId}") !=
                                                          true)
                                                    Padding(
                                                      padding:
                                                          const EdgeInsets.only(
                                                              left: 36,
                                                              bottom: 16),
                                                      child: Container(
                                                          height: 6,
                                                          width: 6,
                                                          decoration:
                                                              const BoxDecoration(
                                                            shape:
                                                                BoxShape.circle,
                                                            color: Colours.main,
                                                          )),
                                                    )
                                                ],
                                              )),
                                      onTap: (value) {
                                        SpUtils.setMatchClick(logic.tabs[value],
                                            "${logic.matchId}");
                                        Utils.onEvent(
                                            '${logic.liveInfo != null ? "liveroom" : "match_detail"}_tab',
                                            params: {'tab': logic.tabs[value]});
                                      },
                                    ),
                                  ),
                                  Expanded(
                                      child: Container(
                                    color: Colours.scaffoldBg,
                                    child: TabBarView(
                                        controller: logic.tabController,
                                        children: List.generate(
                                            logic.pages.length,
                                            (index) => logic.pages[index])),
                                  )),
                                ],
                              ),
                            ),
                          ),
                        ),
                        const GiftEffect()
                      ],
                    ),
                  )));
        });
  }

  liveStreamHeader() {
    return SliverAppBar(
        pinned: true,
        expandedHeight: 199,
        toolbarHeight: 199,
        leading: Container(),
        backgroundColor: Colours.black,
        systemOverlayStyle: const SystemUiOverlayStyle(
            statusBarIconBrightness: Brightness.light),
        flexibleSpace: FlexibleSpaceBar(
          collapseMode: CollapseMode.pin,
          background: SafeArea(
            child: logic.liveInfo?.vtype == 4
                ? AnimateLiveView(liveInfo: logic.liveInfo, sportsId: 2)
                : MatchLiveView(
                    liveInfo: logic.liveInfo,
                    sportsId: 2,
                  ),
          ),
        ));
  }

  matchHeader() {
    return SliverAppBar(
      expandedHeight: 210,
      backgroundColor: Colours.transparent,
      foregroundColor: Colours.white,
      systemOverlayStyle:
          const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.light),
      leading: Styles.backButton(),
      title: logic.showTitle
          ? _barTitle2()
          : Obx(() =>
              Opacity(opacity: logic.opacity.value, child: _barTtitle1())),
      titleTextStyle: const TextStyle(color: Colors.white),
      actions: [
        GestureDetector(
            onTap: () async {
              logic.isFocus = User.basketballFocuses.isFocus(logic.matchId);
              () async {
                if (!logic.isFocus) {
                  Utils.onEvent("match_detail_collect", params: {'collect': 0});
                  await User.basketballFocuses.focus(logic.matchId);
                  logic.isFocus = User.basketballFocuses.isFocus(logic.matchId);
                  Toast.text("关注${logic.isFocus ? "成功" : "失败"}");
                } else {
                  Utils.onEvent("match_detail_collect", params: {'collect': 1});
                  await User.basketballFocuses.unFocus(logic.matchId);
                  logic.isFocus = User.basketballFocuses.isFocus(logic.matchId);
                  Toast.text("取消关注${logic.isFocus ? "失败" : "成功"}");
                }
              }.call();
            },
            child: Image.asset(
              Utils.getImgPath(
                  logic.isFocus ? "match_focus.png" : "match_unfocus.png"),
              color: Colours.white,
              width: 24,
            )),
        Container(width: 8),
        ShareButton(
          route: '/tg/matches/lanqiu/fenxi/${logic.matchId}',
          title:
              "${logic.detail?.awayTeamName} vs ${logic.detail?.homeTeamName}",
          content: "${logic.detail?.matchTime}",
          onTap: () => Utils.onEvent("match_detail_share"),
        ),
        Container(width: 16)
      ],
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        background: Obx(() => Opacity(
              opacity: logic.opacity.value,
              child: LqDetailHeadWidget(
                  detail: logic.detail, id: logic.matchId, logic: logic),
            )),
      ),
    );
  }

  Widget _barTtitle1() {
    final kind = {
      1: '常规赛',
      2: '季后赛',
      3: '季前赛',
      4: '全明星',
      5: '杯赛',
      6: '附加赛'
    }[logic.detail?.kind ?? 0];
    return Column(
      children: [
        DefaultTextStyle(
          style:
              const TextStyle(color: Colors.white, fontSize: 14, height: 1.2),
          child: GestureDetector(
            onTap: () => Get.toNamed(Routes.leagueDetail,
                parameters: {"type": "1"}, arguments: logic.detail?.leagueId),
            child: Column(
              children: [
                if ((logic.detail?.statusId ?? -1) >= 10)
                  QsText(logic.detail?.matchDateTime
                          ?.formatedString('MM-dd HH:mm') ??
                      ""),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QsText(logic.detail?.leagueName ?? ""),
                    if (kind != null)
                      QsText(
                        kind,
                      ).marginOnly(left: 6)
                  ],
                ),
              ],
            ),
          ),
        )
      ],
    );
  }

  Widget _barTitle2() {
    final statusid = logic.detail?.statusId ?? 0;
    // log("detail status id = ${statusid}");
    Widget mid = Container();
    if (statusid == 1) {
      mid = QsText(
          "${logic.detail?.matchDateTime?.formatedString('MM-dd\nHH:mm')}",
          maxLines: 2);
    } else if (statusid == 10) {
      mid = QsText("${logic.detail?.awayScore}-${logic.detail?.homeScore}");
    } else if ((statusid < 1) || (statusid > 8)) {
      mid = QsText(logic.detail?.statusMap[statusid] ?? "");
    } else {
      mid = Column(
        children: [
          QsText(logic.detail?.statusMap[statusid] ?? ""),
          QsText("${logic.detail?.awayScore}-${logic.detail?.homeScore}")
        ],
      );
    }

    return DefaultTextStyle(
        style: const TextStyle(color: Colors.white),
        textAlign: TextAlign.center,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        child: Row(
          children: [
            Expanded(child: QsText(logic.detail?.awayTeamName ?? "")),
            const SizedBox(width: 5),
            mid,
            const SizedBox(width: 5),
            Expanded(child: QsText("${logic.detail?.homeTeamName}[主]")),
          ],
        ));
  }
}
